﻿using CraftParameterConfig.Infrastructure.Common;
using CraftParameterConfig.Infrastructure.Common.Enums;
using CraftParameterConfig.Services.Interfaces;
using CraftParameterConfig.Services.Models;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace CraftParameterConfig.UI.ParameterConfig
{
    public partial class frmParameterConfig : Form
    {
        IParameterService parameterService;
        IParameterAuth parameterAuth;
        ILogInfo logInfo;
        UpdateTypeEnum updateType;
        List<TableIndexDTO> tableIndexDTOs;
        List<TableDataDTO> tableDataDTOs;
        public frmParameterConfig()
        {
            InitializeComponent();
        }

        private void btnSearch_Click(object sender, EventArgs e)
        {
            if (lookNameList.EditValue == null)
            {
                MessageBox.Show("没有选择需要查询的表,请先导入表清单!");
                return;
            }
            //特别注意需要将Columns清空,因为DataSource与Columns是分别独立的
            gvIndexFilter.Columns.Clear();
            var pad = new ParameterAccessDTO() { Status = radStatus.SelectedIndex, FileType = comFileType.SelectedIndex - 1, OrderBatch = txtOrderBatch.Text.Trim(), MaindID = lookNameList.EditValue.ToString() };
            var filters = parameterService.GetParameterAccess(pad);
            if (filters.Count > 990 && radStatus.SelectedIndex == 1)
            {
                btnAddSingle.Enabled = false;
                btnImport.Enabled = false;
                btnCoplySingle.Enabled = false;
                MessageBox.Show("现有可用主数据已超过990条,再次新增将会造成数据查询错误,为避免相关问题,请删除已不再使用的数据,然后再进行新增!");
                return;
            }
            else
            {
                btnAddSingle.Enabled = true;
                btnImport.Enabled = true;
                btnCoplySingle.Enabled = true;
            }
            if (filters.Count > 1000)
            {
                MessageBox.Show("当前可用主数据已超过1000条,请联系管理员!");
                return;
            }
            var dtIndex = parameterService.GetParameterIndexsByCondition(lookNameList.EditValue.ToString(), new Dictionary<Services.Models.TableIndexDTO, string>(), filters);
            gcIndexFilter.DataSource = dtIndex;
            gvIndexFilter.Columns["编号"].Visible = false;
        }

        private void frmParameterConfig_Load(object sender, EventArgs e)
        {
            parameterService = ObjectFactory.GetObject("IParameterService") as IParameterService;
            parameterAuth = ObjectFactory.GetObject("IParameterAuth") as IParameterAuth;
            logInfo= ObjectFactory.GetObject("ILogInfo") as ILogInfo;

            tp_Edit.PageVisible = false;
            tp_Import.PageVisible = false;
            tp_History.PageVisible = false;

            //初始化绑定数据源
            BindDataSource();
        }
        private void BindDataSource()
        {
            DataTable dtNames = parameterService.GetTableName();

            lookNameList.Properties.DisplayMember = "NAME";
            lookNameList.Properties.ValueMember = "GUIDID";
            lookNameList.Properties.DataSource = dtNames;
        }

        private void btnAddSingle_Click(object sender, EventArgs e)
        {
            if (!parameterAuth.GetAddSingleAuth("SC"))
            {
                MessageBox.Show("您没有权限为当前表执行此操作!");
                return;
            }
            groupEdit.Text = string.Format("你正在操作{0}表", lookNameList.Text);
            groupEdit.Enabled = true;
            updateType = UpdateTypeEnum.Add;
            tp_Edit.PageVisible = true;
            tp_Summary.PageVisible = false;
            tc_Main.SelectedTabPage = tp_Edit;

            dateTo.EditValue = null;
            comFileTypeEdit.SelectedIndex = -1;
            txtOrderBatchEdit.Text = "";

            List<ParameterIndexDTO> indexs = new List<ParameterIndexDTO>();
            List<ParameterDataDTO> datas = new List<ParameterDataDTO>();

            foreach (var item in tableIndexDTOs)
            {
                ParameterIndexDTO pid = new ParameterIndexDTO();
                pid.FieldName = item.Name;
                indexs.Add(pid);
            }
            foreach (var item in tableDataDTOs)
            {
                ParameterDataDTO pdd = new ParameterDataDTO();
                pdd.FieldName = item.Name;
                datas.Add(pdd);
            }

            gcIndexEdit.DataSource = indexs;
            gcDataEdit.DataSource = datas;
        }

        private void btnImportMany_Click(object sender, EventArgs e)
        {
            if (!parameterAuth.GetImportRangeAuth("SC"))
            {
                MessageBox.Show("您没有权限为当前表执行此操作!");
                return;
            }
            if (string.IsNullOrEmpty(lookNameList.Text))
            {
                MessageBox.Show("请选择需要导入数据的表!");
                return;
            }
            groupImport.Text = string.Format("你正在操作{0}表", lookNameList.Text);
            updateType = UpdateTypeEnum.Add;
            tp_Import.PageVisible = true;
            tp_Summary.PageVisible = false;
            tc_Main.SelectedTabPage = tp_Import;
        }

        private void btnModifySingle_Click(object sender, EventArgs e)
        {
            if (!parameterAuth.GetAddSingleAuth("SC"))
            {
                MessageBox.Show("您没有权限为当前表执行此操作!");
                return;
            }
            if (gvIndexFilter.SelectedRowsCount <= 0)
            {
                MessageBox.Show("请选择需要修改的数据!");
                return;
            }
            groupEdit.Text = string.Format("你正在操作{0}表", lookNameList.Text);
            groupEdit.Enabled = false;
            gvIndexEdit.OptionsBehavior.Editable = false;
            updateType = UpdateTypeEnum.Modify;
            tp_Edit.PageVisible = true;
            tp_Summary.PageVisible = false;
            tc_Main.SelectedTabPage = tp_Edit;

            ParameterAccessDTO pad = parameterService.GetParameterAccess(gvIndexFilter.GetFocusedDataRow()["编号"].ToString());
            List<ParameterIndexDTO> indexDTOs = parameterService.GetParameterIndexsById(gvIndexFilter.GetFocusedDataRow()["编号"].ToString());
            List<ParameterDataDTO> dataDTOs = parameterService.GetParameterDatasById(gvIndexFilter.GetFocusedDataRow()["编号"].ToString());

            dateTo.Text = pad.Validity.ToString("yyyy/MM/dd");
            comFileTypeEdit.SelectedIndex = pad.FileType;
            txtOrderBatchEdit.Text = pad.OrderBatch;

            gcIndexEdit.DataSource = indexDTOs;
            gcDataEdit.DataSource = dataDTOs;

            gcIndexEdit.RefreshDataSource();
            gcDataEdit.RefreshDataSource();
        }

        private void btnDelete_Click(object sender, EventArgs e)
        {
            if (!parameterAuth.GetDeleteSingleAuth("SC"))
            {
                MessageBox.Show("您没有权限为当前表执行此操作!");
                return;
            }
            if (gvIndexFilter.SelectedRowsCount <= 0)
            {
                MessageBox.Show("请选择需要删除的数据!");
                return;
            }
            if (MessageBox.Show("对主数据的删除可能造成生产无法查询到数据,您确定要执行此操作吗?") == DialogResult.OK)
            {
                ParameterAccessDTO pad = new ParameterAccessDTO() { GuidID = gvIndexFilter.GetFocusedDataRow()["编号"].ToString() };
                parameterService.DeleteParameter(pad);
                MessageBox.Show("删除成功!");
                btnSearch_Click(null, null);
            }
        }

        private void btnCoplySingle_Click(object sender, EventArgs e)
        {
            if (!parameterAuth.GetAddSingleAuth("SC"))
            {
                MessageBox.Show("您没有权限为当前表执行此操作!");
                return;
            }
            groupEdit.Text = string.Format("你正在操作{0}表", lookNameList.Text);
            groupEdit.Enabled = true;
            updateType = UpdateTypeEnum.Add;
            tp_Edit.PageVisible = true;
            tp_Summary.PageVisible = false;
            tc_Main.SelectedTabPage = tp_Edit;

            ParameterAccessDTO pad = parameterService.GetParameterAccess(gvIndexFilter.GetFocusedDataRow()["编号"].ToString());
            List<ParameterIndexDTO> indexDTOs = parameterService.GetParameterIndexsById(gvIndexFilter.GetFocusedDataRow()["编号"].ToString());
            List<ParameterDataDTO> dataDTOs = parameterService.GetParameterDatasById(gvIndexFilter.GetFocusedDataRow()["编号"].ToString());

            dateTo.Text = pad.Validity.ToString("yyyy/MM/dd");
            comFileTypeEdit.SelectedIndex = pad.FileType;
            txtOrderBatchEdit.Text = pad.OrderBatch;

            gcIndexEdit.DataSource = indexDTOs;
            gcDataEdit.DataSource = dataDTOs;

            gcIndexEdit.RefreshDataSource();
            gcDataEdit.RefreshDataSource();
        }

        private void btnAuditMany_Click(object sender, EventArgs e)
        {
            if (!parameterAuth.GetAuditAuth("SC"))
            {
                MessageBox.Show("您没有权限为当前表执行此操作!");
                return;
            }
            if (radStatus.SelectedIndex != 0)
            {
                MessageBox.Show("您只能审核没有审核过的数据!");
                return;
            }
            DataTable dtSource = gcIndexFilter.DataSource as DataTable;
            List<ParameterAccessDTO> pads = new List<ParameterAccessDTO>();
            for (int i = 0; i < dtSource.Rows.Count; i++)
            {
                ParameterAccessDTO pad = new ParameterAccessDTO();
                pad.GuidID = dtSource.Rows[i]["编号"].ToString();
                pad.Status = 1;

                pads.Add(pad);
            }
            var result = parameterService.AuditData(pads);
            LogDTO logDTO = new LogDTO();
            logDTO.KeyWord = result;
            logDTO.Message = "您审核了一批主数据";
            logDTO.LogType = LogType.Info;
            logInfo.SaveLog(logDTO);
            btnSearch_Click(null, null);
        }

        private void btnAuditSingle_Click(object sender, EventArgs e)
        {
            if (!parameterAuth.GetAuditAuth("SC"))
            {
                MessageBox.Show("您没有权限为当前表执行此操作!");
                return;
            }
            if (gvIndexFilter.SelectedRowsCount <= 0)
            {
                MessageBox.Show("请选择需要审核的数据!");
                return;
            }
            var guidid = gvIndexFilter.GetFocusedDataRow()["编号"].ToString();
            ParameterAccessDTO parameterAccessDTO = new ParameterAccessDTO();
            parameterAccessDTO.GuidID = guidid;
            parameterAccessDTO.Status = 1;
            var result = parameterService.AuditData(parameterAccessDTO);
            LogDTO logDTO = new LogDTO();
            logDTO.KeyWord = result;
            logDTO.Message = "您审核了一条主数据";
            logDTO.LogType = LogType.Info;
            logInfo.SaveLog(logDTO);
            btnSearch_Click(null, null);
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            if (sender == null || MessageBox.Show("您确定需要退出当前操作吗?") == DialogResult.OK)
            {
                tp_Summary.PageVisible = true;
                tp_Edit.PageVisible = false;

                tc_Main.SelectedTabPage = tp_Summary;
                updateType = UpdateTypeEnum.None;
                gvIndexEdit.OptionsBehavior.Editable = true;
            }
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            txtLastControl.Focus();
            if (string.IsNullOrEmpty(dateTo.Text) || string.IsNullOrEmpty(comFileTypeEdit.Text))
            {
                MessageBox.Show("请补充完整信息再进行保存!");
                return;
            }
            var indexs = gcIndexEdit.DataSource as List<ParameterIndexDTO>;
            var datas = gcDataEdit.DataSource as List<ParameterDataDTO>;
            if (indexs == null || indexs.Count <= 0)
            {
                MessageBox.Show("请将索引条件补充完整再保存!");
                return;
            }
            if (datas == null || datas.Count <= 0)
            {
                MessageBox.Show("请将值字段补充完整再保存!");
                return;
            }
            foreach (var item in indexs)
            {
                if (!CheckIndexType(item.FieldValue, tableIndexDTOs.Where(t => t.Name == item.FieldName).First()))
                {
                    MessageBox.Show(string.Format("字段[{0}]不满足要求的配置信息,请联系管理员!", item.FieldName));
                    return;
                }
            }
            foreach (var item in datas)
            {
                if (!CheckDataType(item.FieldValue, tableDataDTOs.Where(t => t.Name == item.FieldName).First()))
                {
                    MessageBox.Show(string.Format("字段[{0}]不满足要求的配置信息,请联系管理员!", item.FieldName));
                    return;
                }
            }
            if (updateType == UpdateTypeEnum.Add)
            {
                var pad = new ParameterAccessDTO() { Status = -1, FileType = comFileTypeEdit.SelectedIndex, OrderBatch = txtOrderBatchEdit.Text, Validity = dateTo.DateTime, MaindID = lookNameList.EditValue.ToString() };
                var filters = parameterService.GetParameterAccess(pad);

                Dictionary<Services.Models.TableIndexDTO, string> valuesFilter = new Dictionary<Services.Models.TableIndexDTO, string>();
                foreach (var item in tableIndexDTOs)
                {
                    valuesFilter.Add(item, indexs.Where(t => t.FieldName == item.Name).First().FieldValue);
                }

                var exists = parameterService.IsExist(lookNameList.EditValue.ToString(), valuesFilter, filters);
                if (exists)
                {
                    MessageBox.Show("当前条件主数据已经存在,请重新编辑,或者联系管理员确认!");
                    return;
                }
                var result = parameterService.AddParameterRange(pad, indexs, datas);
                LogDTO logDTO = new LogDTO();
                logDTO.KeyWord = result;
                logDTO.Message = "您新增了一条主数据!";
                logDTO.LogType = LogType.Info;
                logInfo.SaveLog(logDTO);
            }
            else
            {
                var result = parameterService.UpdateData(datas);
                LogDTO logDTO = new LogDTO();
                logDTO.KeyWord = result;
                logDTO.Message = "您修改了一条主数据!";
                logDTO.LogType = LogType.Info;
                logInfo.SaveLog(logDTO);
            }
            btnSearch_Click(null, null);
            btnCancel_Click(null, null);
        }

        private bool CheckIndexType(string value,TableIndexDTO condition)
        {
            IndexDataType indexDataType = (IndexDataType)Enum.Parse(typeof(IndexDataType), condition.DataType);
            DataCondition dataCondition = (DataCondition)Enum.Parse(typeof(DataCondition), condition.DataCondition);

            bool checkResult = false;
            if (string.IsNullOrEmpty(value.Trim()))
            {
                return checkResult;
            }
            switch (indexDataType)
            {
                case IndexDataType.Number:
                    if (dataCondition == DataCondition.Range)
                    {
                        Regex reg = new Regex(@"^[0-9\.]+-[0-9\.]+$");
                        if (reg.IsMatch(value))
                        {
                            checkResult = true;
                        }
                    }
                    else
                    {
                        Regex reg = new Regex(@"^[0-9\.]+$");
                        if (reg.IsMatch(value))
                        {
                            checkResult = true;
                        }
                    }
                    break;
                case IndexDataType.DatTime://日期类型得不能是范围
                    DateTime dR;
                    if (DateTime.TryParse(value, out dR))
                    {
                        checkResult = true;
                    }
                    break;
                case IndexDataType.String://字符串类型得数据,不做限制
                    checkResult = true;
                    break;
                default:
                    break;
                    
            }
            return checkResult;
        }
        private bool CheckDataType(string value, TableDataDTO condition)
        {
            ValueDataType valueDataType = (ValueDataType)Enum.Parse(typeof(ValueDataType), condition.DataType);
            bool checkResult = false;
            switch (valueDataType)
            {
                case ValueDataType.Number:
                    Regex reg = new Regex(@"^[0-9\.]+$");
                    string[] values = value.Split('-');
                    if (condition.NeedBaseValue == "TRUE" && condition.NeedLHValue == "FALSE" && condition.NeedLLHHValue == "FALSE")
                    {
                        if (values.Length == 1 && reg.IsMatch(value))
                        {
                            checkResult = true;
                        }
                    }
                    else if (condition.NeedBaseValue == "TRUE" && condition.NeedLHValue == "TRUE" && condition.NeedLLHHValue == "FALSE")
                    {
                        if (values.Length == 3 && values.All(t=>reg.IsMatch(t)))
                        {
                            checkResult = true;
                        }
                    }
                    else if (condition.NeedBaseValue == "TRUE" && condition.NeedLHValue == "TRUE" && condition.NeedLLHHValue == "TRUE")
                    {
                        if (values.Length == 5 && values.All(t => reg.IsMatch(t)))
                        {
                            checkResult = true;
                        }
                    }
                    else if (condition.NeedBaseValue == "FALSE" && condition.NeedLHValue == "TRUE" && condition.NeedLLHHValue == "FALSE")
                    {
                        if (values.Length == 2 && values.All(t => reg.IsMatch(t)))
                        {
                            checkResult = true;
                        }
                    }
                    else if (condition.NeedBaseValue == "FALSE" && condition.NeedLHValue == "TRUE" && condition.NeedLLHHValue == "TRUE")
                    {
                        if (values.Length == 4 && values.All(t => reg.IsMatch(t)))
                        {
                            checkResult = true;
                        }
                    }
                    else
                    {
                        throw new Exception(string.Format("值字段{0}的配置存在问题,请联系管理员处理!", condition.Name));
                    }
                    break;
                case ValueDataType.DatTime://日期类型得不能是范围
                    DateTime dR;
                    string[] times = value.Split('-');
                    if (condition.NeedBaseValue == "TRUE" && condition.NeedLHValue == "FALSE" && condition.NeedLLHHValue == "FALSE")
                    {
                        if (times.Length == 1 && DateTime.TryParse(value, out dR))
                        {
                            checkResult = true;
                        }
                    }
                    else if (condition.NeedBaseValue == "TRUE" && condition.NeedLHValue == "TRUE" && condition.NeedLLHHValue == "FALSE")
                    {
                        if (times.Length == 3 && times.All(t => DateTime.TryParse(t, out dR)))
                        {
                            checkResult = true;
                        }
                    }
                    else if (condition.NeedBaseValue == "TRUE" && condition.NeedLHValue == "TRUE" && condition.NeedLLHHValue == "TRUE")
                    {
                        if (times.Length == 5 && times.All(t => DateTime.TryParse(t, out dR)))
                        {
                            checkResult = true;
                        }
                    }
                    else if (condition.NeedBaseValue == "FALSE" && condition.NeedLHValue == "TRUE" && condition.NeedLLHHValue == "FALSE")
                    {
                        if (times.Length == 2 && times.All(t => DateTime.TryParse(t, out dR)))
                        {
                            checkResult = true;
                        }
                    }
                    else if (condition.NeedBaseValue == "FALSE" && condition.NeedLHValue == "TRUE" && condition.NeedLLHHValue == "TRUE")
                    {
                        if (times.Length == 4 && times.All(t => DateTime.TryParse(t, out dR)))
                        {
                            checkResult = true;
                        }
                    }
                    else
                    {
                        throw new Exception(string.Format("值字段{0}的配置存在问题,请联系管理员处理!", condition.Name));
                    }
                    break;
                case ValueDataType.String://字符串类型得数据,不做限制
                    checkResult = true;
                    break;
                default:
                    break;
            }
            return checkResult;
        }

        private void lookNameList_EditValueChanged(object sender, EventArgs e)
        {
            tableIndexDTOs = parameterService.GetTableIndexs(lookNameList.EditValue.ToString());
            tableDataDTOs = parameterService.GetTableDatas(lookNameList.EditValue.ToString());
            btnSearch_Click(null, null);
        }

        private void gvDataEdit_FocusedRowChanged(object sender, DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs e)
        {
            var fd = gvDataEdit.GetFocusedRow() as ParameterDataDTO;
            if (fd == null)
            {
                labelEditMessage.Text = "";
            }
            else
            {
                var dataC = tableDataDTOs.Where(t => t.Name == fd.FieldName).First();

                labelEditMessage.Text = string.Format("{0}为{1}类型,需要满足以下规则{2}", dataC.Name, dataC.DataType, GetTypeString(dataC));
            }
        }
        private string GetTypeString(TableDataDTO dataC)
        {
            string typeS = "";
            if (dataC.NeedBaseValue == "TRUE" && dataC.NeedLHValue == "FALSE" && dataC.NeedLLHHValue == "FALSE")
            {
                typeS = "A";
            }
            else if (dataC.NeedBaseValue == "TRUE" && dataC.NeedLHValue == "TRUE" && dataC.NeedLLHHValue == "FALSE")
            {
                typeS = "A-B-C";
            }
            else if (dataC.NeedBaseValue == "TRUE" && dataC.NeedLHValue == "TRUE" && dataC.NeedLLHHValue == "TRUE")
            {
                typeS = "A-B-C-D-E";
            }
            else if (dataC.NeedBaseValue == "FALSE" && dataC.NeedLHValue == "TRUE" && dataC.NeedLLHHValue == "FALSE")
            {
                typeS = "A-B";
            }
            else if (dataC.NeedBaseValue == "FALSE" && dataC.NeedLHValue == "TRUE" && dataC.NeedLLHHValue == "TRUE")
            {
                typeS = "A-B-C-D";
            }
            else
            {
                throw new Exception(string.Format("值字段{0}的配置存在问题,请联系管理员处理!", dataC.Name));
            }
            return typeS;
        }

        private void gvIndexFilter_FocusedRowChanged(object sender, DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs e)
        {
            if (gvIndexFilter.SelectedRowsCount <= 0)
            {
                gcDataView.DataSource = null;
                return;
            }
            string guidId = gvIndexFilter.GetFocusedDataRow()["编号"].ToString();

            List<ParameterDataDTO> datas = parameterService.GetParameterDatasById(guidId);
            gcDataView.DataSource = datas;
            gcDataView.RefreshDataSource();
        }

        private void btnExport_Click(object sender, EventArgs e)
        {
            MessageBox.Show("请特别注意,此模板非常重要,不要修改此模板格式,否则将导致数据导入错误!", "警告!", MessageBoxButtons.OK);
            if (saveFileDialog1.ShowDialog() == DialogResult.OK)
            {
                string fileName = saveFileDialog1.FileName;
                IWorkbook workbook;
                if (fileName.EndsWith(".xlsx"))
                {
                    workbook = new XSSFWorkbook();
                }
                else
                {
                    workbook = new HSSFWorkbook();
                }
                ISheet sheet = workbook.CreateSheet();
                IRow row = sheet.CreateRow(0);
                IRow rowTip = sheet.CreateRow(1);
                //创建ParameterAccess的字段,此类型只需要FileType和Validity两个字段即可
                row.CreateCell(0, CellType.String).SetCellValue("文件类型");
                rowTip.CreateCell(0, CellType.String).SetCellValue("作业指导书/技术通知/工艺文件");
                row.CreateCell(1, CellType.String).SetCellValue("有效期至");
                rowTip.CreateCell(1, CellType.String).SetCellValue("yyyy/MM/dd");
                //创建Index的字段
                for (int i = 0; i < tableIndexDTOs.Count; i++)
                {
                    var cellIndex = row.CreateCell(2 + i, CellType.String);
                    cellIndex.SetCellValue(tableIndexDTOs[i].Name);
                    ICellStyle style = workbook.CreateCellStyle();
                    style.FillForegroundColor = 50;
                    style.FillPattern = FillPattern.SolidForeground;

                    cellIndex.CellStyle = style;
                    rowTip.CreateCell(2 + i, CellType.String).SetCellValue(string.Format("{0}:{1}", tableIndexDTOs[i].DataType, tableIndexDTOs[i].DataCondition));
                }
                //创建Data的字段
                for (int i = 0; i < tableDataDTOs.Count; i++)
                {
                    row.CreateCell(2 + tableIndexDTOs.Count + i, CellType.String).SetCellValue(tableDataDTOs[i].Name);
                    rowTip.CreateCell(2 + tableIndexDTOs.Count + i, CellType.String).SetCellValue(string.Format("{0}:{1}", tableDataDTOs[i].DataType, GetTypeString(tableDataDTOs[i])));
                }

                using (Stream sw = new FileStream(fileName, FileMode.OpenOrCreate, FileAccess.Write))
                {
                    workbook.Write(sw);
                }
                workbook.Close();
                MessageBox.Show("导出成功!");
            }
        }

        private void btnCancelImport_Click(object sender, EventArgs e)
        {
            if (sender == null || MessageBox.Show("您确定需要退出当前操作吗?") == DialogResult.OK)
            {
                tp_Summary.PageVisible = true;
                tp_Import.PageVisible = false;

                tc_Main.SelectedTabPage = tp_Summary;
                updateType = UpdateTypeEnum.None;
            }
        }

        private void btnImport_Click(object sender, EventArgs e)
        {
            MessageBox.Show("请特别注意,此处导入数据模板必须使用导出功能导出的模板,请确保模板格式没有发生过变化,否则将导致导入数据出错!");
            //创建显示的数据源
            DataTable dtSource = new DataTable();
            dtSource.Columns.Add("文件类型");
            dtSource.Columns.Add("有效期至");
            //创建Index字段
            for (int i = 0; i < tableIndexDTOs.Count; i++)
            {
                dtSource.Columns.Add(tableIndexDTOs[i].Name);
            }
            //创建Data字段
            for (int i = 0; i < tableDataDTOs.Count; i++)
            {
                dtSource.Columns.Add(tableDataDTOs[i].Name);
            }
            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                string fileName = openFileDialog1.FileName;
                IWorkbook workbook;
                using (Stream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read))
                {
                    if (fileName.EndsWith(".xlsx"))
                    {
                        workbook = new XSSFWorkbook(fs);
                    }
                    else
                    {
                        workbook = new HSSFWorkbook(fs);
                    }
                    ISheet sheet = workbook.GetSheetAt(0);
                    //要求原始数据Excel的所有单元格必须是字符串类型的,避免因为字段格式造成数据错误
                    //读数时跳过表头
                    for (int i = 1; i < sheet.LastRowNum + 1; i++)
                    {
                        DataRow dr = dtSource.NewRow();
                        IRow row = sheet.GetRow(i);
                        //读取ParameterAccess字段数据
                        ICell cell;
                        cell = row.GetCell(0);
                        cell.SetCellType(CellType.String);
                        dr[0] = cell.StringCellValue;

                        cell = row.GetCell(1);
                        cell.SetCellType(CellType.String);
                        dr[1] = cell.StringCellValue;
                        //读取Index的数据
                        for (int j = 0; j < tableIndexDTOs.Count; j++)
                        {
                            cell = row.GetCell(2 + j);
                            cell.SetCellType(CellType.String);
                            dr[2 + j] = cell.StringCellValue;
                        }
                        //读取Data的数据
                        for (int j = 0; j < tableDataDTOs.Count; j++)
                        {
                            cell = row.GetCell(2 + tableIndexDTOs.Count + j);
                            cell.SetCellType(CellType.String);
                            dr[2 + tableIndexDTOs.Count + j] = cell.StringCellValue;
                        }
                        dtSource.Rows.Add(dr);
                    }

                    gcDataImport.DataSource = dtSource;
                }
            }
        }

        private void btnSaveImport_Click(object sender, EventArgs e)
        {
            //注意,为了程序运行效率和代码简单性,批量导入不验证数据重复性,此功能在获取主数据时进行验证
            if (MessageBox.Show("您将将数据提交审核,请确保数据准确性!") == DialogResult.OK)
            {
                DataTable dtSource = gcDataImport.DataSource as DataTable;

                List<ImportDataDTO> importDataDTOs = new List<ImportDataDTO>();
                for (int i = 0; i < dtSource.Rows.Count; i++)
                {
                    ImportDataDTO importDataDTO = new ImportDataDTO();
                    //生成ParameterAccessDTO的数据
                    ParameterAccessDTO parameterAccessDTO = new ParameterAccessDTO();
                    parameterAccessDTO.FileType = (int)Enum.Parse(typeof(FileType), dtSource.Rows[i][0].ToString());
                    parameterAccessDTO.Validity = Convert.ToDateTime(dtSource.Rows[i][1].ToString());
                    parameterAccessDTO.MaindID = lookNameList.EditValue.ToString();
                    //生成ParameterIndexDTO的数据
                    List<ParameterIndexDTO> parameterIndexDTOs = new List<ParameterIndexDTO>();
                    for (int j = 0; j < tableIndexDTOs.Count; j++)
                    {
                        ParameterIndexDTO parameterIndexDTO = new ParameterIndexDTO();
                        parameterIndexDTO.FieldName = tableIndexDTOs[j].Name;
                        parameterIndexDTO.FieldValue = dtSource.Rows[i][2 + j].ToString();
                        parameterIndexDTOs.Add(parameterIndexDTO);
                        //验证字段是否满足规则
                        if (!CheckIndexType(parameterIndexDTO.FieldValue, tableIndexDTOs.Where(t => t.Name == parameterIndexDTO.FieldName).First()))
                        {
                            MessageBox.Show(string.Format("字段[{0}]不满足要求的配置信息,请联系管理员!", parameterIndexDTO.FieldName));
                            return;
                        }
                    }
                    //生成ParameterDataDTO的数据
                    List<ParameterDataDTO> parameterDataDTOs = new List<ParameterDataDTO>();
                    for (int j = 0; j < tableDataDTOs.Count; j++)
                    {
                        ParameterDataDTO arameterDataDTO = new ParameterDataDTO();
                        arameterDataDTO.FieldName = tableDataDTOs[j].Name;
                        arameterDataDTO.FieldValue = dtSource.Rows[i][2 + tableIndexDTOs.Count + j].ToString();
                        parameterDataDTOs.Add(arameterDataDTO);
                        //验证字段是否满足规则
                        if (!CheckDataType(arameterDataDTO.FieldValue, tableDataDTOs.Where(t => t.Name == arameterDataDTO.FieldName).First()))
                        {
                            MessageBox.Show(string.Format("字段[{0}]不满足要求的配置信息,请联系管理员!", arameterDataDTO.FieldName));
                            return;
                        }
                    }
                    
                    //创建一个完整的DTO元数据
                    importDataDTO.ParameterAccessDTO = parameterAccessDTO;
                    importDataDTO.ParameterIndexDTOs = parameterIndexDTOs;
                    importDataDTO.ParameterDataDTOs = parameterDataDTOs;

                    //将生成好的对象添加进元数据组
                    importDataDTOs.Add(importDataDTO);
                }

                //将元数据保存进数据库
                var result = parameterService.AddParameterRange(importDataDTOs);
                LogDTO logDTO = new LogDTO();
                logDTO.KeyWord = result;
                logDTO.Message = "您批量导入了一些主数据";
                logDTO.LogType = LogType.Info;

                logInfo.SaveLog(logDTO);

                btnCancelImport_Click(null, null);
                btnSearch_Click(null, null);
            }
        }
    }
}
